var timer;

function signIn () {
  nebPay.simulateCall(dappAddress, "0", "getUserInfo", JSON.stringify([]), {
    listener: function(res) {
      if(res.result == '' && res.execute_err == 'contract check failed') {
          toast('合约检测失败，请检查浏览器钱包插件环境！');
          return;
      }
      
      var info = JSON.parse(res.result);
      if (!info) {
        toast('您尚未注册,系统正在自动注册中...');
        register()
      } else {
        renderHtml(info);
        $('#loading').hide();
      }
    }
  })
}

signIn();

function register () {
  nebPay.call(dappAddress, "0", "register", JSON.stringify([]), { 
    listener: function(res) {
      toast(res.txhash ? '大约需要30秒左右,请稍后...' : '注册失败.请刷新页面重试！！！');
      getUserInfo()
    }
  })
}

function getUserInfo () {
  timer = setInterval(function () {
    nebPay.simulateCall(dappAddress, "0", "getUserInfo", JSON.stringify([]), {
      listener: function(res) {
        if(res.result == '' && res.execute_err == 'contract check failed') {
            toast('合约检测失败，请检查浏览器钱包插件环境！');
            return;
        }
        var info = res.result && JSON.parse(res.result);
        if (info) {
          renderHtml(info);
          $('#loading').hide();
          clearInterval(timer);
        }
      }
    })
  }, 5000)
}

function renderHtml (data) {
  var userinfo = JSON.parse(data);
  var html = '';
  for (var i = 0; i < userinfo.token.length; i++) {
    html += '<div class="value"><span>'+userinfo.token[i].tokenName+'</span><span>'+userinfo.token[i].tokenNum+'</span></div>'
  }

  $('#token-list').html(html)
}